﻿using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Threading.Tasks;

namespace DaemonAPI.SchdulerJob
{
	public class Scheduler
	{
		private IScheduler _scheduler;

		public async Task Start()
		{
			await StartJob();
		}

		public async Task StartJob()
		{
			NameValueCollection param = new NameValueCollection()
			{
				{  "UserOrder","UserOrderJob"}
			};

			ISchedulerFactory factory = new StdSchedulerFactory(param);
			_scheduler = await factory.GetScheduler();
			await _scheduler.Start();
			await CreateJob<UserOrderJob>("_UserOrderJob", "_UserOrder", "0/10 * * * * ?");
		}

		public void Stop()
		{
			_scheduler.Shutdown();
			_scheduler = null;
		}

		public async Task CreateJob<T>(string name, string group, string cronTime) where T : IJob
		{
			var job = JobBuilder.Create<T>()
			   .WithIdentity("name" + name, "gtoup" + group)
			   .Build();
			var tigger = (ICronTrigger)TriggerBuilder.Create()
				.WithIdentity("name" + name, "group" + group)
				.StartNow()
				.WithCronSchedule(cronTime)
				.Build();
			await _scheduler.ScheduleJob(job, tigger);
		}
	}
}
